﻿#region Copyright (c) 2006-2012 nHydrate.org, All Rights Reserved
// --------------------------------------------------------------------- *
//                           NHYDRATE.ORG                                *
//              Copyright (c) 2006-2012 All Rights reserved              *
//                                                                       *
//                                                                       *
// This file and its contents are protected by United States and         *
// International copyright laws.  Unauthorized reproduction and/or       *
// distribution of all or any portion of the code contained herein       *
// is strictly prohibited and will result in severe civil and criminal   *
// penalties.  Any violations of this copyright will be prosecuted       *
// to the fullest extent possible under law.                             *
//                                                                       *
// THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
// TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
// TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
// CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
// THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF THE NHYDRATE GROUP *
//                                                                       *
// UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
// PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
// SUBSTANTIALLY THE SAME, FUNCTIONALITY AS THIS PRODUCT                 *
//                                                                       *
// THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
// CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF NHYDRATE,          *
// THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO             *
// INSURE ITS CONFIDENTIALITY.                                           *
//                                                                       *
// THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
// PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
// EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
// THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
// SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                       *
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
// --------------------------------------------------------------------- *
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using nHydrate.Generator.Models;
using nHydrate.Wizard;
using nHydrate.Dsl;
using nHydrate.DataImport;
using System.IO;
using nHydrate.Generator.Common.GeneratorFramework;

namespace nHydrate.DslPackage.Forms
{
	public partial class ImportStaticDataForm : Form
	{
		#region Class Members

		private nHydrate.Dsl.Entity _entity = null;
		private Microsoft.VisualStudio.Modeling.Store _store = null;

		#endregion

		#region Constructors

		public ImportStaticDataForm()
		{
			InitializeComponent();

			wizard1.BeforeSwitchPages += new nHydrate.Wizard.Wizard.BeforeSwitchPagesEventHandler(wizard1_BeforeSwitchPages);
			wizard1.AfterSwitchPages += new nHydrate.Wizard.Wizard.AfterSwitchPagesEventHandler(wizard1_AfterSwitchPages);
			wizard1.Finish += new EventHandler(wizard1_Finish);
			wizard1.FinishEnabled = false;
		}

		public ImportStaticDataForm(nHydrate.Dsl.Entity entity, Microsoft.VisualStudio.Modeling.Store store, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
			: this()
		{
			_entity = entity;
			_store = store;

			lblWelcome.Text = "This wizard will walk you through the process of import static data from a database entity. The database entity schema must match the target function '" + entity.Name + "' in the modelRoot.";

			this.DatabaseConnectionControl1.FileName = Path.Combine((new FileInfo(docData.FileName)).DirectoryName, "importconnection.cache");
			DatabaseConnectionControl1.LoadSettings();
		}

		#endregion

		#region Methods

		private void LoadData(DataTable dt)
		{
			this.dataGridView1.Columns.Clear();
			this.dataGridView1.DataSource = dt;
		}

		public DataTable GetData()
		{
			return (System.Data.DataTable)this.dataGridView1.DataSource;
		}

		#endregion

		#region Event Handlers

		private void wizard1_Finish(object sender, EventArgs e)
		{
			DatabaseConnectionControl1.PersistSettings();

			//using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
			//{
			//  _entity.StaticDatum.Clear();
			//  System.Data.DataTable dt = (System.Data.DataTable)this.dataGridView1.DataSource;
			//  int rowIndex = 0;
			//  foreach (System.Data.DataRow dr in dt.Rows)
			//  {
			//    var columnList = _entity.Fields.ToList();
			//    for (int ii = 0; ii < columnList.Count; ii++)
			//    {
			//      var columnName= columnList[ii].Name;
			//      if (dt.Columns.Contains(columnName))
			//      {
			//        var cellEntry = new StaticData(_entity.Partition);
			//        cellEntry.Value = dr[ii].ToString();
			//        cellEntry.ColumnKey = columnList[ii].Id;
			//        cellEntry.OrderKey = rowIndex;
			//        _entity.StaticDatum.Add(cellEntry);
			//      }
			//    }
			//    rowIndex++;
			//  }

			//  transaction.Commit();
			//}

			this.DialogResult = DialogResult.OK;
			this.Close();
		}

		private void wizard1_AfterSwitchPages(object sender, nHydrate.Wizard.Wizard.AfterSwitchPagesEventArgs e)
		{
			var oldPage = wizard1.WizardPages[e.OldIndex];
			var newPage = wizard1.WizardPages[e.NewIndex];
			wizard1.FinishEnabled = (newPage == pageSummary);
		}

		private void wizard1_BeforeSwitchPages(object sender, nHydrate.Wizard.Wizard.BeforeSwitchPagesEventArgs e)
		{
			var oldPage = wizard1.WizardPages[e.OldIndex];
			var newPage = wizard1.WizardPages[e.NewIndex];

			IImportDomain importDomain = null;
			if (DatabaseConnectionControl1.ImportOptions.Platform == SupportedDatabaseConstants.SqlServer)
				importDomain = new nHydrate.DataImport.SqlClient.ImportDomain();
			else if (DatabaseConnectionControl1.ImportOptions.Platform == SupportedDatabaseConstants.MySql)
				importDomain = new nHydrate.DataImport.MySqlClient.ImportDomain();
			else throw new Exception("Unknown Platform!");
			var databaseHelper = importDomain.DatabaseDomain;

			if ((oldPage == pageImport) && (e.NewIndex > e.OldIndex))
			{
				//Test Connection
				var connectString = DatabaseConnectionControl1.ImportOptions.GetConnectionString();

				var valid = databaseHelper.TestConnectionString(connectString);
				if (!valid)
				{
					MessageBox.Show("The information does not describe a valid connection string.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					e.Cancel = true;
					return;
				}

				//Load the dropdown
				var auditFields = new List<string>();
				var list = importDomain.GetEntityList(connectString);
				cboTable.DataSource = list;
				cboTable.SelectedItem = list.FirstOrDefault(x => x.ToLower() == _entity.Name.ToLower());

			}
			else if ((oldPage == pageChooseTable) && (e.NewIndex > e.OldIndex))
			{
				//Verify that the table schema matches
				var connectionString = DatabaseConnectionControl1.ImportOptions.GetConnectionString();

				var auditFields = new List<SpecialField>();
				var dsValues = databaseHelper.GetStaticData(connectionString, importDomain.GetEntity(connectionString, (string)cboTable.SelectedValue, auditFields));
				this.LoadData(dsValues);
			}

		}

		#endregion

	}
}
